import sys
import array
import time
from threading import Thread
sys.path.append('~/scripts')
from href_parser import HrefParser
from pysvn import Client, depth, ClientError

def Constant(name,value):
    def decorate(func):
        setattr(func,name,int(value))
        return func
    return decorate


@Constant("MAXINMEM", 10000)
class SvnDirectoryDumper():
    def __init__(self,url, output_filename):
        href_parser = HrefParser(url)
        svn_url_list = [href for href in href_parser.get_href_list() if href.find('svn') != -1]
        href_parser.close()
        output_file = open(output_filename, 'w+')
        buff = array.array('c')
        client = Client()

        for svn_url in svn_url_list:
            try:
                for i, s in enumerate(client.list(svn_url, depth=depth.infinity)):
                    try:
                        buff.fromstring(s[0].path + '\n')
                    except UnicodeEncodeError, e:
                        pass
                    
                    if len(buff) > SvnDirectoryDumper.MAXINMEM:
                        buff.tofile(output_file)
                        del buff[:]
                        output_file.flush()
                        
            except ClientError, e:
                    pass


        if len(buff) != 0:
            buff.tofile(output_file)
            del buff[:]
            
        output_file.close()

def process_bar():
    for i in range(100):
        time.sleep(4.6)
        sys.stdout.write("\r%d%%" %i)
        sys.stdout.flush()
    
if __name__ == '__main__':
    if len(sys.argv) > 2:
        input_url = sys.argv[1]
        output_filename = sys.argv[2]

        thread = Thread(target = process_bar, args=[])
        thread.start()
        SvnDirectoryDumper(input_url, output_filename)
    else:
        print "Usage: python svn_directory_dumper <input_url> <output_filename>"
    
   
    
